package com.lzm.ydpt.module.riding.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemap.NETLocationListener;
import com.byt.framlib.basemap.NETLocationManager;
import com.byt.framlib.commonutils.GpsUtils;
import com.byt.framlib.commonutils.permission.PermissionReq;
import com.byt.framlib.commonutils.permission.ResultListener;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.finder.addresswheelfinder.picker.SinglePicker;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.FilterCondition;
import com.lzm.ydpt.entity.riding.PerAddress;
import com.lzm.ydpt.module.common.MapAddressActivity;
import com.lzm.ydpt.mvp.contract.PerAddressContract;
import com.lzm.ydpt.mvp.presenterimpl.PerAddressPresenterImpl;
import com.lzm.ydpt.utils.SelectUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 常驻地址
 */
public class PerAddressActivity extends BaseActivity<PerAddressPresenterImpl> implements NETLocationListener, PerAddressContract.View {
    private static final int address_code = 0x001;
    @BindView(R.id.ntb_per_address)
    NormalTitleBar ntb_per_address;
    @BindView(R.id.tv_per_address_data)
    TextView tv_per_address_data;
    @BindView(R.id.tv_distance_num)
    TextView tv_distance_num;
    @BindView(R.id.mv_per_addrss)
    MapView mv_per_addrss;
    @BindView(R.id.img_center_location)
    ImageView img_center_location;
    private int currentPosition = 0;
    private PoiItem mPoiItem = null;
    private LatLng mLatLng = null;
    private ArrayList<String> array = new ArrayList<>();
    private ArrayList<FilterCondition> tempData = new ArrayList<>();

    private NETLocationManager mManager = null;
    private AMapLocation mLocation = null;
    private AMap mAMap;
    private UiSettings mUiSettings;
    private float zoom = 18;//地图缩放级别
    @Override
    public int getLayoutId() {
        return R.layout.activity_per_address;
    }

    @Override
    public PerAddressPresenterImpl initPreData() {
        return new PerAddressPresenterImpl(this);
    }

    @Override
    public void initView() {
        setNtbTitle(ntb_per_address, false);
        ntb_per_address.setTitleText("常驻地址");
        ntb_per_address.setOnBackListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        initDatas();
        initListener();
        tempData.clear();
        tempData.addAll(Constants.fetDistanceCondition());
        array.clear();
        for (FilterCondition data : tempData) {
            array.add(data.getTitle());
        }
        startLocation();
    }


    @OnClick({R.id.rl_per_address, R.id.rl_per_distance, R.id.tv_save_per_address})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {
            return;
        }
        switch (view.getId()) {
            case R.id.rl_per_address:
                Bundle addressBundle = new Bundle();
                addressBundle.putParcelable(MapAddressActivity.INP_POIITEMS_INFO, mLatLng);
                startActivityForResult(MapAddressActivity.class, addressBundle, address_code);
                break;
            case R.id.rl_per_distance:
                SelectUtil.showDefaultPicker(this, array, "设置活动范围", new SinglePicker.OnItemPickListener<String>() {
                    @Override
                    public void onItemPicked(int index, String item) {
                        tv_distance_num.setText(item);
                        currentPosition = index;
                    }
                }, currentPosition);
                break;
            case R.id.tv_save_per_address:
                showShortToast("保存");
                finish();
                break;
        }

    }

    /**
     * 开始定位
     */
    public void startLocation() {
        PermissionReq.with(this)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        if (!GpsUtils.isOPen(mBContext)) {
                            showShortToast("您未开启手机定位服务，请开启GPS");
                            return;
                        }
                        if (mManager == null) {
                            mManager = new NETLocationManager(mBContext, PerAddressActivity.this);
                        }
                        mManager.start();
                    }

                    @Override
                    public void onDenied() {
                        showShortToast("未开启位置权限，无法获取位置");
                    }
                }).request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == address_code) {
                PoiItem mPoiItem = data.getParcelableExtra(MapAddressActivity.INP_POIITEMS_INFO);
                if (mPoiItem != null) {
                    this.mPoiItem = mPoiItem;
                    mLatLng = new LatLng(mPoiItem.getLatLonPoint().getLatitude(), mPoiItem.getLatLonPoint().getLongitude());
                }
//                tv_hospital_address.setText(mPoiItem.getProvinceName() +
//                        mPoiItem.getCityName() + mPoiItem.getAdName());
                tv_per_address_data.setText(mPoiItem.getProvinceName() +
                        mPoiItem.getCityName() + mPoiItem.getAdName() + mPoiItem.getTitle());

            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        try {
            if (null != aMapLocation) {
                stopLocation();
                if (aMapLocation.getErrorCode() == 0) {//可在其中解析amapLocation获取相应内容。
                    mLocation = aMapLocation;
                    mLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    MyLocationStyle myLocationStyle = new MyLocationStyle()
                            .myLocationIcon(BitmapDescriptorFactory
                                    .fromResource(R.drawable.ic_gps_point))
                            .strokeColor(Color.parseColor("#205eb9ff"))
                            .radiusFillColor(Color.parseColor("#205eb9ff"))
                            .myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
                    myLocationStyle.showMyLocation(true);
                    mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
                    mAMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    private ObjectAnimator mTransAnimator;//地图中心标志动态
    private void initDatas() {
        mv_per_addrss.onCreate(mSavedInstanceState);// 此方法必须重写
        mAMap = mv_per_addrss.getMap();
        mUiSettings = mAMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);//是否显示地图中放大缩小按钮
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        mUiSettings.setScaleControlsEnabled(true);//是否显示缩放级别
        mTransAnimator = ObjectAnimator.ofFloat(img_center_location, "translationY", 0f, -80f, 0f);
        mTransAnimator.setDuration(800);
    }

    private void initListener() {
        //监测地图画面的移动
        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (null != mLatLng && null != cameraPosition ) {
                    zoom = cameraPosition.zoom;
                    startTransAnimator();
                }
            }

            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }
        });
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        if (mManager != null) {
            mManager.onStop();
        }
    }
    /**
     * 移动动画
     */
    private void startTransAnimator() {
        if (null != mTransAnimator && !mTransAnimator.isRunning()) {
            mTransAnimator.start();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mv_per_addrss.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mv_per_addrss.onPause();
    }

    @Override
    public void onStop() {
        if (mManager != null) {
            mManager.onStop();
        }
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mv_per_addrss.onSaveInstanceState(outState);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        stopLocation();
        mv_per_addrss.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onPerAddress(PerAddress perAddress) {

    }

    @Override
    public void onSaveAddress(String msg) {

    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
    }

    @Override
    public void showErrorView(String msg) {

    }
}
